import 'package:flutter_again/models/video_info.dart';
import 'package:flutter_again/models/video_platform.dart';
import 'package:flutter_again/models/video_search_params.dart';
import 'package:flutter_again/models/video_search_result.dart';
import 'package:flutter_again/parsers/interfaces/video_platform_parser.dart';
import 'package:flutter_again/utils/dom_parse.dart';
import 'package:flutter_again/utils/log.dart';
import 'package:html/dom.dart';
import 'package:http/http.dart' as http;

class JavmenuParser extends VideoPlatformParser {
  @override
  final String platformId = 'javMenu';
  @override
  VideoPlatform get platformInfo => VideoPlatform.javmenu;
  final client = http.Client();
  final categoryCodeMap = {
    '已审查': 'censored',
    '未审查': 'uncensored',
    '欧美': 'western',
    'FC2': 'fc2',
    '动画': 'hanime',
    '国产': 'chinese',
  };

  String getUrl(VideoSearchParams params) {
    String url = '${platformInfo.rootUrl}/zh';
    String query = params.query;
    int page = params.page;
    String category = params.category ?? '';
    if (query.isNotEmpty) {
      url += '?wd=$query';
    } else {
      category = category.isNotEmpty ? category : '已审查';
      var categoryCode = categoryCodeMap[category];
      url += '/$categoryCode/online';
    }
    url += query.isNotEmpty ? '&page=$page' : '?page=$page';
    return url;
  }

  @override
  Future<VideoSearchResult> search(VideoSearchParams params) async {
    final url = getUrl(params);
    log.d('url: $url');
    var page = params.page;
    var hasNextPage = false;
    var res = await client.get(Uri.parse(url));
    final doc = domParse(res.body);
    final itemList = doc.querySelectorAll('.category-page');
    List<VideoInfo> list = itemList.sublist(1).map((item) {
      final logoEle = item.querySelector('.card-img-top');
      final thumbnailUrl = logoEle?.attributes['data-src'] ?? '';
      final linkEle = item.querySelector('.card-body a');
      final linkUrl = linkEle?.attributes['href'] ?? '';
      final title = linkEle?.querySelector('p')?.text ?? '';
      final year = linkEle?.querySelector('.text-muted')?.text ?? '';
      return VideoInfo(
        id: linkUrl,
        platform: platformId,
        title: title,
        detailUrl: linkUrl,
        thumbnailUrl: thumbnailUrl,
        year: year,
      );
    }).toList();
    var pageItems = doc.querySelectorAll('.pagination .page-item');
    for (final item in pageItems) {
      final linkItem = item.querySelector('.page-link');
      final href = linkItem?.attributes['href'] ?? '';
      final pageNumStr = href.split('page=').last;
      final pageNum = pageNumStr.isNotEmpty ? int.parse(pageNumStr) : 0;
      // if (item.classes.contains('active')) {
      //   page = int.parse(linkItem?.text ?? '1');
      // }
      if (pageNum > page) {
        hasNextPage = true;
        break;
      }
    }

    return VideoSearchResult(
      platform: platformId,
      videos: list,
      currentPage: page,
      hasNextPage: hasNextPage,
    );
  }
  @override
  Future<VideoInfo> getVideoDetail(String url) async {
    final res = await client.get(Uri.parse(url));
    final doc = domParse(res.body);
    final videoUrl = getVideoUrlByDoc(doc);
    return VideoInfo(
      id: url,
      platform: platformId,
      title: '',
      thumbnailUrl: '',
      detailUrl: url,
      videoUrl: videoUrl,
    );
  }

  @override
  getVideoUrl(String pageUrl) async {
    final res = await client.get(Uri.parse(pageUrl));
    final doc = domParse(res.body);
    return getVideoUrlByDoc(doc);
  }

  String getVideoUrlByDoc(Document doc) {
    var script = doc.querySelector('.tab-pane.active script')?.text ?? '';
    final videoUrl = script.trim().split('"')[1];
    return videoUrl;
  }
}
